﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.Utils;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.IO;
using System.Web.SessionState;
using System.Data;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class LabourRelation : System.Web.UI.Page
    {
        private Main main = new Main();
        private SsMng creatby = new SsMng();
        private ILabourRelationBLL CreatLabourRelation = new LabourRelationBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ChangeMode(Main.EditMode.View);

                int? intFileSeq = main.ConvertNullInt(lblUploadSeq.Text);
                cboCategory.DataSource = CreatLabourRelation.LoadCategory();
                cboCategory.DataBind();
                cboCategory.Items.Insert(0, new RadComboBoxItem("กรุณาเลือกหมวดหมู่", ""));
            }
        }

        private void ChangeMode(Main.EditMode mode)
        {
            switch (mode)
            {
              case Main.EditMode.AddNew:
                    pnlGridLabour.Visible = false;
                    pnlGridLabourAdd.Visible = true;
                    btnSubmit.Visible = true;
                    btnUpdate.Visible = false;
                    btnCancle.Visible = true;
                    break;

                case Main.EditMode.View:
                    pnlGridLabour.Visible = true;
                    pnlGridLabourAdd.Visible = false;
                    btnSubmit.Visible = false;
                    btnUpdate.Visible = true;
                    btnCancle.Visible = true;
                    break;

                case Main.EditMode.Edit:
                    pnlGridLabour.Visible = false;
                    pnlGridLabourAdd.Visible = true;
                    break;
            }
        }

        private void ClearControlData()
        {
            cboCategory.SelectedIndex = 0;
            txtRemark.Text = "";
            txtFileName.Text = "";
        }

        private bool CheckNullValue()
        {
            bool bOk = true;

            if (cboCategory.SelectedValue.Length == 0)
            {
                main.MessageAlert(Page, "กรุณาเลือกหมวดหมู่");
                bOk = false;
            }
            else if (txtFileName.Text == "")
            {
                main.MessageAlert(Page, "กรุณากรอกชื่อไฟล์");
                bOk = false; 
            }
            return bOk;
        }

        protected void dgtGridLabour_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "GridDelete")
            {
                GridDataItem item = (GridDataItem)e.Item;

                int? intFileSeq = main.ConvertNullInt(item["upload_file_seq"].Text);
                int? intUploadSeq = main.ConvertNullInt(item["upload_category_seq"].Text);
                string strFileUploadName = DateTime.Now.Ticks.ToString() + (FileUpload.FileName);
                string strFileName = item["file_name"].Text;
                string strTrashPath = ("../UploadFiles/Trash/");
                string strFolderName = item["upload_category_seq"].Text;
                string strPath = ("../UploadFiles/");
                string NewPath = (strPath + strFolderName + "/");
                string path = (NewPath + strFileName);
                string strFilePath = item["file_path"].Text;
                string strFileExtension = new FileInfo(Server.MapPath(strFilePath)).Extension;
                string strFileTrash = (strTrashPath + strFileUploadName + strFileExtension);

                DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath(strTrashPath));

                if (!DirInfo.Exists)
                {
                    DirInfo.Create();
                }


                CreatLabourRelation.Delete(intFileSeq, strFileTrash, creatby.EmpSeqI); 

                if (File.Exists(Server.MapPath(strFilePath)))
                {
                    File.Move((Server.MapPath(strFilePath)), Server.MapPath(strTrashPath + strFileUploadName + strFileExtension));
                }

                LoadFileUpload();
                ChangeMode(Main.EditMode.View);
            }
            else if (e.CommandName == "GridEdit")
            {
                ChangeMode(Main.EditMode.Edit);
                GridDataItem item = (GridDataItem)e.Item;

                lblUploadSeq.Text = (item["upload_file_seq"].Text);
                cboCategory.SelectedValue = (item["upload_category_seq"].Text);
                string strFileName = main.WebString((item["file_name"].Text));
                string strFilePath = item["file_path"].Text;
                ViewState["file_path"] = item["file_path"].Text;
                txtRemark.Text = item["remark"].Text;
                string strFolderName = item["upload_category_seq"].Text;
                string strPath = ("../UploadFiles/");
                string NewPath = (strPath + strFolderName + "/");
                string path = (NewPath + strFileName);
                txtFileName.Text = strFileName;
            }

            else if (e.CommandName == "download_file")
            {
                GridDataItem item = (GridDataItem)e.Item;

                string strFolderName = item["upload_category_seq"].Text;
                string strPath = ("../UploadFiles/");
                string NewPath = (strPath + strFolderName + "/");
                string strFileName = item["file_name"].Text;
                string strFilePath = item["file_path"].Text;
                string strFileExtension = new FileInfo(Server.MapPath(strFilePath)).Extension;
                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(strFilePath + strFileExtension) + "\"");
                byte[] data = req.DownloadData(MapPath(strFilePath));
                response.BinaryWrite(data);
                response.End();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int? intFileSeq = main.ConvertNullInt(lblUploadSeq.Text);
            string strFileName = txtFileName.Text;
            string strFileUploadName = DateTime.Now.Ticks.ToString() + (FileUpload.FileName);
            string strRemark = txtRemark.Text;
            int? intUploadSeq = main.ConvertNullInt(cboCategory.SelectedValue);
            string strFilePath = ("../UploadFiles/" + cboCategory.SelectedValue + "/" + strFileUploadName);
            string strPath = ("../UploadFiles/");
            string strFolderName = cboCategory.SelectedValue;
            string NewPath = (strPath + strFolderName + "/");
            string strFileExtension = new FileInfo(Server.MapPath(strFilePath)).Extension;

            if (!CheckNullValue())
            {
                return;
            }
 
            DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath(strPath +"\\"+ strFolderName));

            if (!DirInfo.Exists)
            {
                DirInfo.Create();
            }

            bool CheckValueSubmit = CreatLabourRelation.CheckValueSubmit(intFileSeq);
            if (CheckValueSubmit == true)
            {
                if (this.FileUpload.HasFile)
                {

                    if (strFileExtension == ".exe")
                    {
                        main.MessageAlert(Page, "ไม่สามารถอัพโหลดไฟล์ที่มีนามสกุลเป็น .exe ได้");
                        return;
                    }
                    else
                    {
                        HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                        double maxFileSize = Math.Round(section.MaxRequestLength * 1024.0, 1);
                        if (FileUpload.PostedFile.ContentLength <= maxFileSize)
                        {
                            CreatLabourRelation.Insert(intUploadSeq, strFileName, strFilePath, strRemark, creatby.EmpSeqI);
                            this.FileUpload.SaveAs(Server.MapPath(NewPath + strFileUploadName));
                        }
                        else
                        {
                            main.MessageAlert(Page, "เกิดข้อผิดพลาดในการอัพโหลด");
                            return;
                        }
                    }
                }
                else
                {
                    main.MessageAlert(Page, "กรุณาเลือกไฟล์ในการอัพโหลด");
                    return;

                }
                
                main.MessageAlert(Page, "อัพโหลดเรียบร้อยแล้ว");
            }

            LoadFileUpload();
            ChangeMode(Main.EditMode.View);
        }

        protected void dgtGridLabour_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            int? intUploadSeq = main.ConvertNullInt(cboCategory.SelectedValue);
            dgtGridLabour.DataSource = CreatLabourRelation.Search(null, intUploadSeq, null, null, null);
        }

        public void LoadFileUpload ()
        {
            string strFileName = DateTime.Now.Ticks.ToString() + (FileUpload.FileName);
            string value = strFileName;
            string[] lines = Regex.Split(value, DateTime.Now.Ticks.ToString());
            int? intUploadSeq = main.ConvertNullInt(cboCategory.SelectedValue);

            dgtGridLabour.DataSource = CreatLabourRelation.Search(null, intUploadSeq, null, null, null);
            dgtGridLabour.DataBind();
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            ClearControlData();
            ChangeMode(Main.EditMode.AddNew);
        }

        protected void btnCancle_Click(object sender, EventArgs e)
        {
            ChangeMode(Main.EditMode.View);
            LoadFileUpload();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int? intFileSeq = main.ConvertNullInt(lblUploadSeq.Text);
            int? intUploadSeq = main.ConvertNullInt(cboCategory.SelectedValue);
            string strFileName = txtFileName.Text;
            string strRemark = txtRemark.Text;
            string strFileUploadName = DateTime.Now.Ticks.ToString() + (FileUpload.FileName);
            string strFilePath = ("../UploadFiles/" + cboCategory.SelectedValue + "/" + strFileUploadName);
            string strDiffstrFilePath = (ViewState["file_path"].ToString());
            string strPath = ("../UploadFiles/");
            string strFolderName = cboCategory.SelectedValue;
            string NewPath = (strPath + strFolderName + "/");
            string strTrashPath = ("../UploadFiles/Trash/");
            string strFileExtension = new FileInfo(Server.MapPath(strFilePath)).Extension;
            if (!CheckNullValue())
            {
                return;
            }
 
            DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath(strPath +"\\"+ strFolderName));

            if (!DirInfo.Exists)
            {
                DirInfo.Create();
            }

            bool CheckValueSubmit = CreatLabourRelation.CheckValueSubmit(intFileSeq);
            if (CheckValueSubmit == true)
            {

                if (this.FileUpload.HasFile)
                {
                    if (strFileExtension == ".exe")
                    {
                        main.MessageAlert(Page, "ไม่สามารถอัพโหลดไฟล์ที่มีนามสกุลเป็น .exe ได้");
                        return;
                    }

                        HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                        double maxFileSize = Math.Round(section.MaxRequestLength * 1024.0, 1);
                        if (FileUpload.PostedFile.ContentLength <= maxFileSize)
                        {
                            CreatLabourRelation.Update(intFileSeq, intUploadSeq, strFileName, strFilePath, strRemark,
                                                       creatby.EmpSeqI);
                            this.FileUpload.SaveAs(Server.MapPath(NewPath + strFileUploadName));
                           
                        }
                        else
                        {
                            main.MessageAlert(Page, "เกิดข้อผิดพลาดในการอัพโหลด");
                            return;
                        }
                 }
                else
                {
                    main.MessageAlert(Page, "กรุณาเลือกไฟล์ในการอัพโหลด");
                    return;
                }

                main.MessageAlert(Page, "อัพโหลดเรียบร้อยแล้ว");
            }

            DirectoryInfo DirInfo1 = new DirectoryInfo(Server.MapPath(strTrashPath));

            if (!DirInfo1.Exists)
            {
                DirInfo1.Create();
            }

            if (File.Exists(Server.MapPath(strFilePath)))
            {
                File.Move((Server.MapPath(strDiffstrFilePath)), Server.MapPath(strTrashPath + strFileUploadName));
            }

            LoadFileUpload();
            ChangeMode(Main.EditMode.View);
        }
     }
}